package com.ck.juc;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 自实现原子操作
 */
public class SpinLock {

    private AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public void lock() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "\t come in lock");
        while (!atomicBoolean.compareAndSet(false,true)){
        }
    }

    public void unLock() {
        System.out.println(Thread.currentThread().getName() + "\t come out unLock");
        while (!atomicBoolean.compareAndSet(true,false)){
        }
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                spinLock.lock();
                Thread.sleep(1000*1);
                spinLock.unLock();
            }
        },"aa").start();

        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                spinLock.lock();
                Thread.sleep(1000*2);
                spinLock.unLock();
            }
        },"bb").start();
    }
}
